package com.qf.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class ParamInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 获取必传参数有哪些
        Set paramSet = redisTemplate.opsForSet()
                .members("api:param");

        //2. 从request对象中获取实际发送的参数集合
        HashSet<String> requestSet = new HashSet<>();
        // 获取所有请求头中的参数的名字
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            requestSet.add(headerName);
        }

        //获取请求参数的名字
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> keySet = parameterMap.keySet();

        requestSet.addAll(keySet);

        // 比对是否所有必传参数都传了
        paramSet.removeAll(requestSet);

        if (paramSet.size()>0){
            log.info("必传参数缺少了"+paramSet);
            // 如果必传参数集合中有元素剩余，说明少传了参数了
            throw new RuntimeException("必传参数缺失："+paramSet);
        }else {
            return true;
        }

    }
}
